package com.zhongkeruan.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhongkeruan.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangyao
 * @Description: 网关全局拦截器
 * @date 2019/1/17 14:25
 */
@Component
public class GolbalFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        return true;
    }

    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        String user_agent = request.getHeader("user-agent");
        int startIndex=user_agent.indexOf("(");
        int endIndex=user_agent.indexOf(")");
        String deviceStr= user_agent.substring(startIndex+1, endIndex);

        String token = request.getHeader("access_token");
        String uri = request.getRequestURI();
        if (uri.contains("login")){
            return null;
        }
        if (StringUtils.isEmpty(token)){
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            context.setSendZuulResponse(false); //终止转发，返回响应报文
            context.setResponseStatusCode(400);
            Map<String,String> responseMap=new HashMap<String,String>();
            responseMap.put("errorcode", "401");
            responseMap.put("errorMsg", "未认证");
            context.setResponseBody(JSON.toJSONString(responseMap));
        }else{
            try{
                Claims claims = jwtUtil.parseToken(token);
                String role = (String) claims.get("role");
                Date loginDate = claims.getIssuedAt();
                String userName = (String) claims.getSubject();
                System.out.println("用户名："+userName+",角色："+role+",登录时间："+loginDate);
                //这里可以进一步校验token的合法性、时效性，甚至对报文进行校验
                context.setSendZuulResponse(true); //将请求往后转发
                context.setResponseStatusCode(200);
                context.addZuulRequestHeader("access_token",token);
            }catch (Exception e){
                response.setHeader("Content-Type", "application/json;charset=UTF-8");
                context.setSendZuulResponse(false); //终止转发，返回响应报文
                context.setResponseStatusCode(400);
                Map<String,String> responseMap=new HashMap<String,String>();
                responseMap.put("errorcode", "402");
                responseMap.put("errorMsg", "token已过期");
                context.setResponseBody(JSON.toJSONString(responseMap));
            }
        }
        return null;
    }
}
